5<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElPagination } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { 
  Camera, 
  InfoFilled,
  Check,
  CirclePlusFilled 
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const form = { username: route.params.username || '普通用户' }

const detectionRecords = ref<any[]>([])
const isLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(2)
const totalRecords = computed(() => detectionRecords.value.length)

const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return [...detectionRecords.value]
    .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
    .slice(start, end)
})

// 从后端获取检测记录
const fetchRecords = async () => {
  isLoading.value = true
  try {
    const response = await axios.get('/detection/user_records', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      }
    })
    detectionRecords.value = response.data
  } catch (error) {
    ElMessage.error('获取检测记录失败')
    console.error('获取检测记录失败:', error)
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  fetchRecords()
})

// 获取最近4条记录
const recentRecords = computed(() => {
  return [...detectionRecords.value]
    .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
    .slice(0, 4)
})
// 获取最高概率的疾病预测结果
const getMainPrediction = (prediction: any) => {
  const entries = Object.entries(prediction)
  const [mainDisease, maxProb] = entries.reduce((max, entry) => 
    parseFloat(entry[1] as string) > parseFloat(max[1] as string) ? entry : max
  )
  return {
    disease: mainDisease,
    probability: parseFloat(maxProb as string)
  }
}
// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleDateString()
}

const startDetection = () => {
  router.push('/upload')
  ElMessage({ message: '正在跳转至检测上传页面...', type: 'info' })
}
</script>

<template>
  <div class="user-dashboard-container">
    <header class="dashboard-header">
      <h1 class="page-title">我的眼部健康管理</h1>
      <span class="user-name">{{ form.username || '普通用户' }}</span>
    </header>

    <div class="dashboard-content">
      <div class="records-list">
        <div class="section-header">
          <h2 class="section-title">检测记录</h2>
          <span class="record-count">共 {{ totalRecords }} 条记录 (当前显示 {{ paginatedRecords.length }} 条)</span>
        </div>
        
        <div v-if="!detectionRecords.length" class="empty-state">
          <el-icon class="empty-icon"><CirclePlusFilled /></el-icon>
          <p class="empty-text">暂无检测记录，点击"开始检测"按钮上传眼部影像</p>
        </div>
        
        <div v-else>
          <div class="records-container">
            <div 
              v-for="record in paginatedRecords" 
              :key="record.id" 
              class="record-card"
            >
            <div class="record-info">
              <div class="record-type">眼部健康检测</div>
              <div class="record-result" :class="`result-tag result-${getMainPrediction(record.prediction).disease === '正常' ? 'normal' : 'warning'}`">
                {{ getMainPrediction(record.prediction).disease }}
              </div>
              <div class="record-meta">
                <span class="meta-item">检测日期: {{ formatDate(record.created_at) }}</span>
                <span class="meta-item">可信度: {{ (getMainPrediction(record.prediction).probability * 100).toFixed(1) }}%</span>
              </div>
            </div>
            </div>
          </div>
          <el-pagination
            v-if="detectionRecords.length > pageSize"
            v-model:current-page="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next"
            :total="totalRecords"
            class="pagination-container"
          />
        </div>
      </div>
      
      <div class="action-area">
        <div class="action-card">
          <h3 class="action-title">快速操作</h3>
          <el-button 
            type="primary" 
            class="detect-btn"
            @click="startDetection"
          >
            <el-icon class="btn-icon"><Camera /></el-icon>
            开始检测
          </el-button>
        </div>
        
        <div class="tips-card">
          <div class="card-header">
            <el-icon class="card-icon"><InfoFilled /></el-icon>
            <h3 class="tips-title">健康小贴士</h3>
          </div>
          <ul class="tips-list">
            <li><el-icon><Check /></el-icon>建议每6个月进行一次眼部健康检测</li>
            <li><el-icon><Check /></el-icon>长时间用眼后应休息10-15分钟</li>
            <li><el-icon><Check /></el-icon>保持充足睡眠，避免熬夜伤眼</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 全局重置与基础布局 */
.user-dashboard-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: #fafafa;
  font-family: "Microsoft YaHei", sans-serif;
  width: 80vw;
  margin: 0 auto;
}

/* 顶部标题栏 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 32px;
  background: linear-gradient(120deg, #e8f4f8, #ffffff);
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  border-radius: 8px;
  margin: 20px;
}

.page-title {
  font-size: 2.4rem;
  font-weight: 700;
  background: linear-gradient(90deg, #165DFF 0%, #36D399 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  position: relative;
  text-shadow: 
    0 0 10px rgba(22,93,255,0.2),
    0 0 20px rgba(54,211,153,0.2);
  animation: glitch 3s infinite;
}

@keyframes glitch {
  0% { transform: translate(0,0); }
  2% { transform: translate(-2px,2px); opacity: 0.9; }
  4% { transform: translate(2px,-2px); opacity: 0.9; }
  6% { transform: translate(-2px,-2px); opacity: 0.9; }
  8% { transform: translate(2px,2px); opacity: 0.9; }
  10% { transform: translate(0,0); opacity: 1; }
  100% { transform: translate(0,0); }
}

.user-name {
  font-size: 14px;
  color: #555;
}

/* 主内容区 */
.dashboard-content {
  display: flex;
  gap: 20px;
  padding: 0 20px 20px;
}

/* 记录列表 */
.records-list {
  flex: 2;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.02);
  padding: 20px;
}

/* 操作区域 */
.action-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.action-card, .tips-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.action-title {
  font-size: 16px;
  font-weight: 600;
  color: #34495e;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.card-icon {
  margin-right: 8px;
  color: #3498db;
  font-size: 18px;
}

.tips-list li {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.tips-list li:last-child {
  border-bottom: none;
}

.tips-list li .el-icon {
  color: #36D399;
  font-size: 14px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #34495e;
}

.record-count {
  font-size: 14px;
  color: #7f8c8d;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 240px;
}

.empty-icon {
  font-size: 48px;
  color: #3498db;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
  color: #999;
  text-align: center;
}

.records-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.01);
  transition: all 0.3s ease;
}

.record-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(52,152,219,0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.pagination-container .el-pagination {
  --el-pagination-bg-color: #f5f7fa;
  --el-pagination-button-disabled-bg-color: #f5f7fa;
}

.record-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.record-type {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.result-tag {
  font-size: 12px;
  padding: 4px 12px;
  border-radius: 16px;
  display: inline-block;
}

.result-normal {
  background-color: rgba(46, 204, 113, 0.1);
  color: #2ecc71;
}

.result-warning {
  background-color: rgba(243, 156, 18, 0.1);
  color: #f39c12;
}

.record-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 13px;
  color: #7f8c8d;
}

.detect-btn {
  width: 100%;
  padding: 12px;
  font-size: 14px;
  background: linear-gradient(90deg, #3498db, #2980b9);
  border: none;
  border-radius: 8px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: transform 0.2s ease, box-shadow 0.3s ease;
}

.detect-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(52,152,219,0.3);
}

.tips-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.01);
}

.tips-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  position: relative;
  padding-left: 20px;
}

.tips-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: #3498db;
  border-radius: 2px;
}

.tips-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tips-list li {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}
</style>